package com.zzc.alfred.entity.job;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.zzc.alfred.entity.model.ProductIndexModel;
import com.zzc.alfred.entity.service.index.ProductIndexModelIndexService;
import com.zzc.alfred.entity.service.mysql.ProductIndexModelDBService;

/**
 * 每天定时同步数据 從抓取的產品庫中間提取數據
 * 
 * @author famous
 *
 */
public class SyncCrawlProductJob implements Job {

	Logger logger = Logger.getLogger(SyncCrawlProductJob.class);

	static ProductIndexModelIndexService indexService = new ProductIndexModelIndexService();

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		List<ProductIndexModel> addModels = new ArrayList<ProductIndexModel>();
		List<ProductIndexModel> updateModels = new ArrayList<ProductIndexModel>();
		logger.info("开始同步数据");
		// 查询新增的或者修改的数据
		List<ProductIndexModel> models = getAddModels();
		// 针对新增的和修改的分别执行索引的新增和更新
		for (ProductIndexModel model : models) {
			if (indexService.getProduct(model.getId())) {
				updateModels.add(model);
			} else {
				addModels.add(model);
			}
		}
		logger.info("addModels's size" + addModels.size());
		logger.info("updateModels's  size" + updateModels.size());
		indexService.addProduct(addModels);
		indexService.updateProduct(updateModels);
		logger.info("停止同步数据");
	}

	private List<ProductIndexModel> getAddModels() {
		ProductIndexModelDBService indexModelService = new ProductIndexModelDBService();
		return indexModelService.getAddedProduct();
	}

	public static void main(String[] args) {
		SyncCrawlProductJob crawlProductJob = new SyncCrawlProductJob();
		try {
			crawlProductJob.execute(null);
		} catch (JobExecutionException e) {
			e.printStackTrace();
		}
	}
}
